﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;

namespace MockupDesigner.AppItems.Commands
{
    public class DeleteCommand : ICommand
    {

        private DesignerCanvas designerCanvas;

        private IList<DesignerItem> deletedItems = new List<DesignerItem>();
        private Dictionary<DesignerItem, int> allItems = new Dictionary<DesignerItem, int>();

        public CommandType CommandType
        {
            get { return CommandType.Undoable; }
        }

        public void Execute(object target, params object[] parameters)
        {
            if (!(target is DesignerCanvas))
            {
                throw new InvalidCastException("The target must be a DesignerCanvas");
            }
            this.designerCanvas = (DesignerCanvas)target;

            Redo();
        }

        public void Redo()
        {
            if (this.allItems.Count == 0) // save the ZIndex of every item in the canvas
            {
                foreach (DesignerItem item in this.designerCanvas.Children.OfType<DesignerItem>())
                {
                    allItems.Add(item, Canvas.GetZIndex(item));
                }
            }
            if (deletedItems.Count == 0) // get the items to delete if firstime that the command is executed
            {
                deletedItems = new List<DesignerItem>((from ISelectable item in this.designerCanvas.SelectionService.CurrentSelection
                                                       select item as DesignerItem).ToList());
            }
            this.designerCanvas.SelectionService.ClearSelection();
            foreach (DesignerItem item in this.deletedItems) // remove the items to delete
            {
                this.designerCanvas.Children.Remove(item);
            }
            this.designerCanvas.UpdateZIndex();
        }

        public void Undo()
        {
            foreach (DesignerItem elem in this.deletedItems) // restore the deleted items
            {
                if (!this.designerCanvas.Children.Contains(elem))
                {
                    this.designerCanvas.Children.Add(elem);
                }
            }
            foreach (DesignerItem item in this.allItems.Keys) // restore the ZIndex saved for every item
            {
                Canvas.SetZIndex(item, this.allItems[item]);
            }
        }

    }
}
